package com.ionehe.group.common.uaa.ex.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * Copyright (c) 2021 IONEHE.COM
 * Date: 2021/8/3
 * Time: 4:00 下午
 *
 * @author 2021年 <a href="mailto:a@ionehe.com">秀</a>
 * 【date工具类】
 */
public class DateUtil {
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    public static Date asDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static LocalDateTime now() {
        return LocalDateTime.now();
    }

    public static LocalDateTime todayEnd() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
    }

    public static LocalDateTime todayStart() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
    }

    public static Date getTheHour(Date date) {
        return asDate(asLocalDateTime(date).withMinute(0).withSecond(0).withNano(0));
    }

    public static Date timestamp2Date(String time) {
        Timestamp ts = new Timestamp(Long.parseLong(time));
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return dateFormat.parse(dateFormat.format(ts));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
